package com.testdocs.client.common.dialog.base;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
import com.testdocs.client.common.i18n.CommonConstants;
import com.testdocs.client.validation.ConstraintViolationException;

public class BaseDialog {

	private static BaseDialogUiBinder uiBinder = GWT
			.create(BaseDialogUiBinder.class);

	@UiTemplate("BaseDialog.ui.xml")
	interface BaseDialogUiBinder extends
			UiBinder<Widget, BaseDialog> {
	}

	ActionConfirmedHandler handler;

	@UiField
	DialogBox dialogBox;

	@UiField
	SimplePanel panel;
	
	DialogPanel dialogPanel;
	
	@UiField
	Button okButton;
	@UiField
	Button cancelButton;

	private CommonConstants commonConstants = (CommonConstants) GWT
			.create(CommonConstants.class);

	public BaseDialog(String header, DialogPanel dialogPanel, ActionConfirmedHandler handler) {
		this.handler = handler;
		uiBinder.createAndBindUi(this);
		dialogBox.setText(header);
		okButton.setText(commonConstants.ok());
		cancelButton.setText(commonConstants.cancel());
		panel.setWidget(dialogPanel);
		this.dialogPanel = dialogPanel;
	}
	
	public BaseDialog(DialogPanel dialogPanel) {
		this(null, dialogPanel, null);
	}

	@UiHandler("cancelButton")
	void handleCancel(ClickEvent e) {
		hide();
	}

	@UiHandler("okButton")
	void handleOk(ClickEvent event) {
		if (handler == null) {
			hide();
		} else {
			try {
				handler.handle();
				hide();				
			} catch (ConstraintViolationException e) {
				dialogPanel.handleValidationConstraints(e.getValidationConstraints());
			}
		}
	}

	public void show() {
		dialogBox.center();
		dialogBox.show();
	}
	
	public void show(String header) {
		dialogBox.setText(header);
		show();
	}

	public void hide() {
		dialogBox.hide();
		dialogPanel.clear();
	}
	
	public void setHandler(ActionConfirmedHandler handler) {
		this.handler = handler;
	}
	
	public interface ActionConfirmedHandler extends EventHandler {
		public void handle() throws ConstraintViolationException;
	}
}
